#############################################################
#							Welcome							#
#		Tsinghua University Course System in Python			#
#						 Version: v1.0 						#
#						Date: 2015/04/09					#
#			By: Haoyu hu	Email: im@huhaoyu.com			#
#				Address: Tsinghua University				#
#############################################################

import urllib.request, urllib.parse, http.cookiejar
import re, sys, codecs
import urllib.error

def create_opener():
	cookie = http.cookiejar.CookieJar()
	cookie_proc = urllib.request.HTTPCookieProcessor(cookie)
	urllib.request.install_opener(urllib.request.build_opener(cookie_proc))

def get_response(url, post):
	if post != '':
		request = urllib.request.Request(url, post.encode())
		try:
			response = urllib.request.urlopen(request)
		except urllib.error.HTTPError as e:
			print ('THE SERVER COULD NOT FULFILL THE REQUEST, PLEASE CHECK YOUR NETWORK')
			sys.exit(1)
		except urllib.error.URLError as e:
			print ('WE FAILED TO REACH A SERVER, PLEASE CHECK YOUR NETWORK')
			sys.exit(1)
	else:
		try:
			response = urllib.request.urlopen(url)
		except urllib.error.HTTPError as e:
			print ('THE SERVER COULD NOT FULFILL THE REQUEST, PLEASE CHECK YOUR NETWORK')
			sys.exit(1)
		except urllib.error.URLError as e:
			print ('WE FAILED TO REACH A SERVER, PLEASE CHECK YOUR NETWORK')
			sys.exit(1)
	return response.read()

def login(username, password):
	url = 'https://portal.tsinghua.edu.cn/Login'
	post = 'userName=' + username + '&password=' + password + '&x=0&y=0'
	create_opener()
	ret = get_response(url, post)
	slist = re.findall('\w{36}', ret.decode())
	if slist == []:
		print ('USERNAME OR PASSWORD IS INCORRECT, PLEASE TRY AGAIN')
		sys.exit(1)
	return slist[5]

def get_coursetable(ticket):
	url = 'http://zhjw.cic.tsinghua.edu.cn/j_acegi_login.do?url=/jxmh.do&m=yjs_kbSearch&ticket=' + ticket
	ret = get_response(url, '').decode('gb2312')
	done = re.findall('[\u4E00-\u9FA5]+\d[ABC]*\d+|[\u4E00-\u9FA5]+[（]*[\u4E00-\u9FA5]+[）]*|\d-\d[\u4E00-\u9FA5]', ret)
	if '请重试' in done:
		return False
	save, count = '', 0
	courses = []
	print('-' * 50)
	print('教师\t课类型\t周次\t上课地点\t课程名称')
	print('-' * 50)
	for i in range(1, len(done)):
		if done[i] == '开课信息查询':
			break
		if count == 3:	
			save += done[i] + ' ' * (6 - len(done[i])) + '\t'
		else:
			save += done[i] + '\t'
		if count == 4:
			courses.append(save)
			save, count = '', 0
		else:
			count += 1
	
	courses = set(courses)
	for line in courses:
		print (line)
	print('-' * 50)

	return True

def logout():
	url = 'http://portal.tsinghua.edu.cn/Logout'
	response = get_response(url, '')

def tucourse():
	username = '2014210130'
	password = '123456'

	print ('FETCHING DATA FROME http://info.tsinghua.edu.cn, PLEASE WAIT A MOMENT...\n')

	count = 1
	done = False
	while not done:
		done = True
		ticket = login(username, password)
		if not get_coursetable(ticket):
			done = False
		logout()

if __name__ == '__main__':
	tucourse()